import axios from "axios";
import website from "@/const/website";
import { serialize } from "@/util";
import { aesDecrypt, aesEncrypt } from "@/util/encryption";
import { getStore } from "@/util/store";
import NProgress from "nprogress"; // progress bar
import errorCode from "@/const/errorCode";
// eslint-disable-next-line
import router from "@/router/router";
import { Message, MessageBox } from "element-ui";
import "nprogress/nprogress.css";
import qs from "qs";
import store from "@/store"; // progress bar style
axios.defaults.timeout = 30000;
// 返回其他状态吗
axios.defaults.validateStatus = function (status) {
  return status >= 200 && status <= 500; // 默认的
};
// 跨域请求，允许保存cookie
axios.defaults.withCredentials = true;
// NProgress Configuration
NProgress.configure({
  showSpinner: false,
});

// HTTPrequest拦截
axios.interceptors.request.use(
  (config) => {
    NProgress.start(); // start progress bar
    const TENANT_ID = getStore({ name: "tenantId" });
    const isToken = (config.headers || {}).isToken === false;
    const token = store.getters.access_token;

   
    if (token && !isToken) {
      config.headers["Authorization"] = "Bearer " + token; // token
    }
   

    if (TENANT_ID) {
      config.headers["TENANT-ID"] = TENANT_ID; // 租户ID
    }

    // headers中配置serialize为true开启序列化
    if (config.method === "post" && config.headers.serialize) {
      config.data = serialize(config.data);
      delete config.data.serialize;
    }

    // 请求报文加密
    if (config.headers["Enc-Flag"]) {
      config.data = {
        encryption: aesEncrypt(
          JSON.stringify(config.data),
          website.encPassword
        ),
      };
    }

    if (config.method === "get") {
      config.paramsSerializer = function (params) {
        return qs.stringify(params, { arrayFormat: "repeat" });
      };
    }

    return config;
  },
  (error) => {
    return Promise.reject(error);
  }
);

//防抖函数
function debounce(fn, delay = 500) {
  let timer;
  return function (...args) {
    if (timer) {
      clearTimeout(timer);
    }
    const that = this;
    timer = setTimeout(() => {
      fn.apply(that, args);
    }, delay);
  };
}

//使用防抖函数拦截令牌过期
const debouncedToken = debounce(TokenExpiration);

//令牌过期函数处理
function TokenExpiration(...args) {
  MessageBox.confirm("令重新登录牌状态已过期，请点击重新登录", "系统提示", {
    confirmButtonText: "重新登录",
    cancelButtonText: "取消",
    type: "warning",
  })
    .then(() => {
      console.log(123);

      router.push({ path: "/login" });
      // store.dispatch("LogOut").then(() => {
      //   //新增路由跳转回到登录页面
      //   router.push({ path: "/login" });
      //   // 刷新登录页面，避免多次弹框
      window.location.reload();
      // });
    })
    .catch(() => {});
}

function goPage() {
  if (window.$wujie) {
    const { info } = window.$wujie.props;
    const { url } = info;

    console.log("访问子应用路由地址host1", url);
    this.$router.push({
      path: "/",
    });
    setTimeout(() => {
      this.$router.push({
        path: url,
      });
    }, 500);
  }
}

// HTTPresponse拦截
axios.interceptors.response.use(
  (res) => {
    NProgress.done();
    const status = Number(res.status) || 200;
    const message = res.data.msg || errorCode[status] || errorCode["default"];

    console.log("res.data.code", res.data.code);

    if (res.data.code == 401) {
       

      // 通知主应用刷新 token
      window.$wujie.bus.$emit("token:expired");

      // 等待主应用返回新 token 后重试请求
      return new Promise((resolve) => {
        window.$wujie.bus.$once("token:refresh", () => {
          const newToken = localStorage.getItem("infomng-access_token-1");

          console.log("newToken", JSON.parse(newToken).accessToken);
          res.config.headers.Authorization = `Bearer ${
            JSON.parse(newToken).accessToken
          }`;
          resolve(axios(res.config)); // 重试原请求
        });

        // 如果主应用刷新失败，触发登出
        window.$wujie.bus.$once("token:logout", () => {
          resolve(Promise.reject(error));
        });
      });
    }

 

    // 后台定义 424 针对令牌过去的特殊响应码
    if (status === 424) {
      //wujie 处理子应用登陆过期问题
      if (window.__POWERED_BY_WUJIE__) {
        window.$wujie.props.jump(); // 调用主应用传进来的方法
      } else {
        MessageBox.confirm("令牌状态已过期，请点击重新登录", "系统提示", {
          confirmButtonText: "重新登录",
          cancelButtonText: "取消",
          type: "warning",
        })
          .then(() => {
            store.dispatch("LogOut").then(() => {
              // 刷新登录页面，避免多次弹框
              window.location.reload();
            });
          })
          .catch(() => {});
      }

      return;
    }

    if (status !== 200 || res.data.code === 1) {
      Message({
        message: message,
        type: "error",
      });
      return Promise.reject(new Error(message));
    }

    // 针对密文返回解密
    if (res.data.encryption) {
      const originData = JSON.parse(
        aesDecrypt(res.data.encryption, website.encPassword)
      );
      res.data = originData;
      return res;
    }

    return res;
  },
  (error) => {
    // 处理 503 网络异常
    if (error.response.status === 503) {
      Message({
        message: error.response.data.msg,
        type: "error",
      });
    }
    NProgress.done();
    return Promise.reject(new Error(error));
  }
);

export default axios;
